package com.louis.ylog.feign;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import com.louis.ylog.TraceContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Component;

/**
 * 适用于使用feign调用其他SpringCloud微服务的调用链上下文传递场景
 * 作用：在使用feign请求其他微服务时，自动生成context上下文，并将相应参数rootId、parentId、childId放入header
 * 使用方法：在需要添加catcontext的feign service接口中，@FeignClient注解添加此类的configuration配置，
 *      如：@FeignClient(name="account-manage", configuration = CatFeignConfiguration.class)
 *
 * @author soar
 * @date 2019-01-10
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "ylog.cat.enable-cat", havingValue = "true")
@EnableFeignClients(defaultConfiguration = CatFeignConfiguration.class)
@ConditionalOnMissingBean(RequestInterceptor.class)
public class CatFeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        if(TraceContext.isCatEnable()){
            try {

                //创建caller端cross报表
                createCallerCross(requestTemplate.url());

                CatContextImpl catContext = new CatContextImpl();
                Cat.logRemoteCallClient(catContext,Cat.getManager().getDomain());
                requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_ROOT_MESSAGE_ID,catContext.getProperty(Cat.Context.ROOT));
                requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_PARENT_MESSAGE_ID,catContext.getProperty(Cat.Context.PARENT));
                requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_CHILD_MESSAGE_ID,catContext.getProperty(Cat.Context.CHILD));

                requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_Request_Domain,Cat.getManager().getDomain());

            }catch (Exception ex){
                log.error("feign跨服务调用CAT配置异常",ex);
            }
        }
    }

    private void createCallerCross(String url){
        try {
            //cross 报表
            Transaction crossT=Cat.newTransaction(CatConstantsExt.CROSS_CONSUMER,url);
            String serverName=TraceContext.getEnv() +"-service-"+ url.split("/")[1];
            Cat.logEvent(CatConstantsExt.CONSUMER_CALL_APP , serverName);
            Cat.logEvent(CatConstantsExt.CONSUMER_CALL_SERVER, serverName);
            Cat.logEvent(CatConstantsExt.CONSUMER_CALL_PORT,"8080");
            crossT.setStatus(Transaction.SUCCESS);
            crossT.complete();
//
//            //transaction报表
//            Transaction feignT=Cat.newTransaction("Feign.Call",url);
//            feignT.setStatus(Transaction.SUCCESS);
//            feignT.complete();

        }catch (Exception ex){
            log.error("feign创建cross报表异常",ex);
        }
    }


}
